package com.atqar.rwlock;

/*写线程首先获取写锁，更新数据，然后将锁降级为读锁。读线程在获取读锁后读取数据。
这个过程演示了锁降级的概念，允许多个线程在持有读锁的情况下同时访问数据，
提高了并发性能。`
请注意，在锁降级期间，我们要确保数据的一致性，即在降级为读锁之前和之后都可以正确读取数据。
这是锁降级的关键部分。（先获取读锁，再释放写锁）*/


import java.util.concurrent.locks.ReentrantReadWriteLock;

class lockdon{

    ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    int a=0;
    public void upadta(int b){
        writeLock.lock();
        try {
            a=b;
            System.out.println("修改数据为"+b);
            readLock.lock();
            System.out.println("抢到读锁读更新的内容");
        }finally {
            writeLock.unlock();
        }
        try {
            int c= readData();
            System.out.println("读到更新的数据"+c);
        }finally {
            readLock.unlock();
        }

    }

    public int readData() {
       readLock.lock();
        try {
            return a;
        } finally {
          readLock.unlock();
        }
    }


}
public class ReadWriteDownLoceDemo2 {

    public static void main(String[] args) {
        lockdon lockdon = new lockdon();
        new Thread(()->{
            lockdon.upadta(666);
        }).start();

        new Thread(()->{
            int read = lockdon.readData();
            System.out.println("读到更新的数据为"+read);
        }).start();

    }
}
